package com.woniu.teachmall04.service;

import com.woniu.teachmall04.entity.User;
import com.woniu.teachmall04.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MinioService minioService;

    // 登录
    public User login(String account, String password) {
        User user = userMapper.selectByAccount(account);
        if(user == null) {
            return null;
        }
        String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        if(user.getPassword().equals(encryptedPassword)) {
            return user;
        }
        return null;
    }

    // 注册
    public boolean register(String account, String password, String email, String telphone) {
        if(userMapper.selectByAccount(account) != null) {
            return false;
        }

        User user = new User();
        user.setAccount(account);
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        user.setEmail(email);
        user.setTelephone(telphone);
        user.setPoints(0);
        user.setMoney(BigDecimal.valueOf(0.0));
        user.setAvatar("default.jpg");
        user.setRegTime(LocalDateTime.now());
        user.setStatus("Y");

        return userMapper.insertUser(user) > 0;
    }

    // 更新用户信息
    public boolean updateUserInfo(User user) {
        return userMapper.updateUser(user) > 0;
    }

    // 修改密码
    public boolean changePassword(Integer userId, String oldPassword, String newPassword) {
        User user = userMapper.selectById(userId);
        if(!user.getPassword().equals(DigestUtils.md5DigestAsHex(oldPassword.getBytes()))) {
            return false;
        }
        return userMapper.updatePassword(userId, DigestUtils.md5DigestAsHex(newPassword.getBytes())) > 0;
    }

    // 上传头像
    public String uploadAvatar(MultipartFile file) throws Exception {
        return minioService.uploadFile(file);
    }
}